package com.share.dymamic.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.share.dymamic.datasource.DataSourceContextHolder;
import com.share.dymamic.entity.Entity;
import com.share.dymamic.repository.EntityRepository;

/** 
* @author weigen.ye 
* @date 创建时间：2016年10月8日 下午5:46:52 
*
*/
@Service
public class EntityService {

	@Resource
    private EntityRepository repository;
	
	public void insert(Entity entity){
		this.repository.insert(entity);
	}
	
	public void update(Integer id,String status){
	    repository.update(id, status);
	}
	
    public List<Entity> select() {
    	List<Entity> list=repository.selectAll();
		return list;
    }
	    
    public Entity selectByKey(Integer id) {
    	List<Entity> list=repository.selectByKey(id);
    	if(list!=null){
    		return list.get(0);
    	}
    	return null;
    }
    
    public List<Entity>  selectBetweenKeys(Integer sItemId,Integer eItemId){
    	List<Entity> list=repository.selectBetweenKeys(sItemId, eItemId);
    	return list;
    }
    
    @Transactional(rollbackFor=RuntimeException.class)
    public void firstWirteThanRead(Integer writeId,String status,Integer readId){
    	DataSourceContextHolder.setDataSource("ds_write");
    	Entity entity=new Entity();
    	entity.setId(writeId);
    	entity.setStatus(status);
    	repository.insert(entity);
    	if(readId==9){
    		throw new RuntimeException();
    	}
//    	DataSourceContextHolder.setDataSource("ds_read");
//    	Long s=System.currentTimeMillis();
//    	System.out.println("cost "+(System.currentTimeMillis()-s)+"ms"+repository.selectByKey(readId));
    }
}
